<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="选择日期" prop="date">
        <el-date-picker v-model="dateTime" :disabled="disabled" type="month" placeholder="请选择月份">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="仓库名称" prop="warehouseName">
        <el-select v-model="queryParams.warehouseCode" filterable  placeholder="请输入仓库名称" clearable>
          <el-option v-for="item in WareList" :key="item.wareCode" :label="item.wareName" :value="item.wareCode">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"  v-hasPermi="['system:PartsWarehouse:add']">新增</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:PartsWarehouse:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:PartsWarehouse:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"  v-hasPermi="['system:PartsWarehouse:Export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      <div class="textNuM" v-if="this.allMoney > 0 && !cpShow">开票总金额：<span class="kpNum"> {{ formatNumber(this.allMoney)
          }}</span></div>
      <div class="textNuM" v-if="cpShow">销售总金额：<span class="kpNum"> {{ formatNumber(this.sumMoney) }}</span>
      </div>
    </el-row>

    <el-table v-loading="loading" :data="PartsWarehouseList" @selection-change="handleSelectionChange" border>
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column prop="index" label="序号" width="55" align="center"></el-table-column>
      <!-- <el-table-column label="仓库编码" align="center" prop="warehouseCode" />-->
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="供应商" align="center" prop="provide" />
      <el-table-column label="产品编码" align="center" prop="productCode" width="140" />
      <el-table-column label="产品名称" align="center" prop="productName" width="150" />
      <el-table-column label="数量" align="center" prop="productCount" width="120">
        <template slot-scope="scope">
          <span class="textNum"> {{ scope.row.productCount > 0 ? parseFloat(scope.row.productCount).toFixed(2) : 0 }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="进价" align="center" prop="plarnPrice" width="120" v-if="!cpShow">
        <template slot-scope="scope">
          <span class="textNum"> {{ formatNumber(scope.row.plarnPrice > 0 ? parseFloat(scope.row.plarnPrice).toFixed(2)
      :
      '-') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="售价" align="center" prop="productPrice" width="120">
        <template slot-scope="scope">
          <span class="textNum"> {{ formatNumber(scope.row.productPrice > 0 ?
      parseFloat(scope.row.productPrice).toFixed(2) : '-') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="采购金额" align="center" prop="productMoney" width="120" v-if="!cpShow">
        <template slot-scope="scope">
          <span class="textNum" style="color:red"> {{ formatNumber(scope.row.productMoney > 0 ?
      parseFloat(scope.row.productMoney).toFixed(2) : '-') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="销售金额" align="center" prop="productMoney" width="120" v-if="cpShow">
        <template slot-scope="scope">
          <span class="textNum" style="color:red"> {{ formatNumber(scope.row.productPrice > 0 ?
      parseFloat(scope.row.productPrice * scope.row.productCount).toFixed(2) : '-') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="品牌" align="center" prop="productBrand" />

      <el-table-column label="规格" align="center" prop="specs" width="130" />
      <el-table-column label="型号" align="center" prop="model" width="130" />
      <el-table-column label="结算模式" align="center" prop="settlementMode" />
      <!-- <el-table-column label=" 封账">
        <template slot-scope="scope">
          <el-button type="text" size="small" :disabled="scope.row.otherMoney !== 0 || scope.row.isFz === true"
            @click="sealAccounts(scope.row)">
            封账
          </el-button>
        </template>
</el-table-column> -->
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" plain icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <div class="NumAll">
      <div class="textNuM1" v-if="this.allMoney > 0 && !cpShow">采购总金额：<span class="kpNum"> {{
      formatNumber(this.allMoney)
    }}</span>
      </div>
      <div class="textNuM1" v-if="this.sumMoney > 0 && !cpShow">销售总金额：<span class="kpNum"> {{
      formatNumber(this.sumMoney)
    }}</span>
      </div>
      <div class="textNuM1" v-if="this.productPrice > 0 && !cpShow">利润总金额：<span class="kpNum"> {{
      formatNumber(parseFloat(this.productPrice).toFixed(2))
    }}</span></div>
    </div>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改配件库开票明细对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :show-close="false" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="10" class="mb8">
          <el-col :span="12">
            <el-form-item label="仓库编码" prop="warehouseCode">
              <el-input v-model="form.warehouseCode" placeholder="请输入仓库编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库名称" prop="warehouseName">
              <el-input v-model="form.warehouseName" placeholder="请输入仓库名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品编码" prop="productCode">
              <el-input v-model="form.productCode" placeholder="请输入产品编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="售价" prop="productPrice">
              <el-input v-model="form.productPrice" placeholder="请输入售价" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="进价" prop="plarnPrice">
              <el-input v-model="form.plarnPrice" placeholder="请输入进价" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="productCount">
              <el-input v-model="form.productCount" placeholder="请输入数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金额" prop="productMoney">
              <el-input v-model="form.productMoney" placeholder="请输入金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="productBrand">
              <el-input v-model="form.productBrand" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="provide">
              <el-input v-model="form.provide" placeholder="请输入供应商" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格" prop="specs">
              <el-input v-model="form.specs" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号" prop="model">
              <el-input v-model="form.model" placeholder="请输入型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结算模式" prop="settlementMode">
              <el-input v-model="form.settlementMode" placeholder="请输入结算模式" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPartsWarehouse, getPartsWarehouse, delPartsWarehouse, addPartsWarehouse, updatePartsWarehouse, wareList } from "@/api/system/PartsWarehouse";
import { updateRecords } from "@/api/system/records";
export default {
  name: "PartsWarehouse",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 配件库开票明细表格数据
      PartsWarehouseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseCode: null,
        warehouseName: null,
        productCode: null,
        productName: null,
        productPrice: null,
        plarnPrice: null,
        productCount: null,
        productMoney: null,
        productBrand: null,
        provide: null,
        specs: null,
        model: null,
        settlementMode: null,
        status: null,
        startTime: ''
      },
      cpShow: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        warehouseCode: [
          { required: true, message: '请输入仓库编码', trigger: 'blur' }
        ],
        warehouseName: [
          { required: true, message: '请输入仓库名称', trigger: 'blur' }
        ],
        productCode: [
          { required: true, message: '请输入产品编码', trigger: 'blur' }
        ],
        productName: [
          { required: true, message: '请输入产品名称', trigger: 'blur' }
        ],
        productPrice: [
          { required: true, message: '请输入售价', trigger: 'blur' }
        ],
        plarnPrice: [
          { required: true, message: '请输入进价', trigger: 'blur' }
        ],
        productCount: [
          { required: true, message: '请输入数量', trigger: 'blur' }
        ],
        productMoney: [
          { required: true, message: '请输入金额', trigger: 'blur' }
        ],
        productBrand: [
          { required: true, message: '请输入品牌', trigger: 'blur' }
        ],
        provide: [
          { required: true, message: '请输入供应商', trigger: 'blur' }
        ],
        specs: [
          { required: true, message: '请输入规格', trigger: 'blur' }
        ],
        model: [
          { required: true, message: '请输入型号', trigger: 'blur' }
        ],
        settlementMode: [
          { required: true, message: '请输入结算模式', trigger: 'blur' }
        ]
      },
      // 仓库下拉
      WareList: [],
      // 日期
      dateTime: [],
      // 按钮权限
      disabled: false,
      shouldFetchData: false,
      // 开票总金额
      allMoney: '',
      // 利润总金额
      productPrice: "",
      // 销售总金额
      sumMoney: "",
      // 角色
      deptName: "",

      fisrtActivate: true
    };
  },
  created() {
    this.eventHnadling();
  },
  activated() {
    if(!this.fisrtActivate) {
      if(this.queryParams.provide!== this.$route.query.provide) {
        this.eventHnadling();
        this.queryParams.pageNum = 1;
      }
    } else {
      // 防止 重复请求
      this.fisrtActivate = false;
    }
  },

  methods: {
    eventHnadling() {
      const User = localStorage.getItem('User');
      this.deptName = JSON.parse(User).dept ? JSON.parse(User).dept.deptName : '';
      if (this.deptName !== '物资公司') {
        this.queryParams.provide = this.deptName;
      } else {
        this.queryParams.provide = "";
      }
      if (this.$route.query.cpShow) {
        this.cpShow = this.$route.query.cpShow
      }
      this.FormData();
      this.getList();
      this.wareList();
    },


    /** 查询配件库开票明细列表 */
    getList() {
      this.loading = true;
      // 将日期字符串转换为日期对象
      const dateObj = new Date(this.dateTime);
      // 获取年份和月份
      const year = dateObj.getFullYear();
      const month = dateObj.getMonth() + 1;

      // 格式化月份为两位数
      const formattedMonth = month < 10 ? `0${month}` : `${month}`;

      // 格式化日期
      const formattedStartDate = `${year}-${formattedMonth}`;

      if (this.$route.query.provide) {
        this.queryParams.provide = this.$route.query.provide;
        if (this.queryParams.provide) {
          this.disabled = true;
        }
      } else {
        this.queryParams.provide = "";
      }
      if (this.$route.query.dateTime) {
        this.disabled = true;
      }
      console.log(this.$route.query.provide);
      this.queryParams.warehouseCode = this.$route.query.warehouseCode ? this.$route.query.warehouseCode : this.queryParams.warehouseCode;
      this.queryParams.startTime = this.$route.query.dateTime ? this.$route.query.dateTime : formattedStartDate;
      listPartsWarehouse(this.queryParams,).then(response => {
        this.allMoney = localStorage.getItem('summoney') ? parseFloat(localStorage.getItem('summoney')).toFixed(2) : 0;
        this.sumMoney = localStorage.getItem('totalmoney') ? parseFloat(localStorage.getItem('totalmoney')).toFixed(2) : 0;
        this.productPrice = this.sumMoney - this.allMoney;
        this.total = response.data.total;
        this.PartsWarehouseList = response.data.list;
        this.PartsWarehouseList.forEach((item, index) => {
          item.index = (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
        })
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        warehouseCode: null,
        warehouseName: null,
        productCode: null,
        productName: null,
        productPrice: null,
        plarnPrice: null,
        productCount: null,
        productMoney: null,
        createTime: null,
        productBrand: null,
        provide: null,
        specs: null,
        model: null,
        settlementMode: null,
        status: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.warehouseCode = "";
      this.FormData();
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加配件库开票明细";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPartsWarehouse(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改配件库开票明细";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePartsWarehouse(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPartsWarehouse(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除配件库开票明细编号为"' + ids + '"的数据项？').then(function () {
        return delPartsWarehouse(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/provideRecords/export', {
        ...this.queryParams
      }, `产品明细${this.queryParams.startTime}.xlsx`)
    },
    // 封账
    sealAccounts(row) {
      this.$confirm('是否进行封装?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = {
          provide: row.provide,
          status: "1"
        }
        updateRecords(params).then(rst => {
          if (rst.code === 200) {
            this.getList();
            this.$message({
              type: 'success',
              message: '封账成功!'
            });

          } else {
            this.$message({
              type: 'error',
              message: '封账失败!'
            });
          }
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消封账'
        });
      });
    },
    // 仓库下拉
    wareList() {
      wareList().then(rst => {
        this.WareList = rst.data
      })
    },
    FormData() {
      // 定义一个函数,用于格式化日期为"yyyy-MM"
      const formatDate = date => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        return `${year}-${month}`;
      };

      // 获取当前日期
      const currentDate = new Date();
      const lastMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1);

      // 设置dateTime的初始值为当前年月,并格式化为"yyyy-MM"
      this.dateTime = this.$route.query.dateTime ? this.$route.query.dateTime : formatDate(lastMonth);
    },
    formatNumber(value) {
      if (value) {
        let [integerPart, decimalPart] = value.toString().split('.');
        let formattedNumber = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',') + '.' + decimalPart.slice(0, 3);
        return formattedNumber;
      }

    }
  }
};
</script>
<style lang="scss" scoped>
.textNum {
  float: right;
}

.NumAll {
  position: absolute;
  z-index: 999;
  margin-top: 10px;
  display: flex;

  .textNuM1 {
    margin-right: 15px;
    font-size: 15px;
    margin-top: 3px;
    color: #c0c4cc;

    .kpNum {
      font-weight: 600;
      color: red;
    }
  }
}

.textNuM {
  float: right;
  margin-right: 15px;
  font-size: 15px;
  margin-top: 3px;
  color: #c0c4cc;

  .kpNum {
    font-weight: 600;
    color: red;
  }
}
</style>
